package com.lt.flashcard.model.service;

import org.zkoss.lang.Threads;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.Messagebox;

/**
 * Push notification from server to client
 * @author ocsen
 */
public class NotificationUpdater {

    public static void start(Component container) {
        final Desktop desktop = Executions.getCurrent().getDesktop();
        if (!desktop.isServerPushEnabled()) {
            desktop.enableServerPush(true);
            new WorkingThread(container);
        }
    }

    public static void stop() {
        final Desktop desktop = Executions.getCurrent().getDesktop();
        if (desktop.isServerPushEnabled()) {
            desktop.enableServerPush(false);
        }
    }

    /**
     * Do push notification
     * @author ocsen
     *
     */
    private static class WorkingThread extends Thread {

        private Component container = null;

        private WorkingThread(Component ctn) {
            this.container = ctn;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    if (container.getDesktop() == null || !container.getDesktop().isServerPushEnabled()) {
                        return;
                    }

                    Messagebox.show("Thread");
                    Threads.sleep(5000);
                }
            } catch (Exception e) {
            }
        }
    }
}
